import Vue from 'vue'
import VueRouter from 'vue-router'
import { getToken } from '@/utils/storage'
import { Toast } from 'vant'

const Register = () => import('@/views/Register.vue')
const Layout = () => import('@/views/Layout.vue')
const Login = () => import('@/views/Login.vue')
const Detail = () => import('@/views/Detail.vue')
const Article = () => import('@/views/Article.vue')
const Collect = () => import('@/views/Collect.vue')
const Like = () => import('@/views/Like.vue')
const User = () => import('@/views/User.vue')

Vue.use(VueRouter)

// 配置一级路由
const routes = [
  { path: '/', redirect: '/article' },
  { path: '/register', component: Register },
  { path: '/login', component: Login },
  { path: '/detail/:id', component: Detail },
  {
    path: '/',
    component: Layout,
    children: [
      { path: '/article', component: Article },
      { path: '/collect', component: Collect },
      { path: '/like', component: Like },
      { path: '/user', component: User }
    ]
  }

]

const router = new VueRouter({
  routes
})
const whiteList = ['/login', '/register']
// 导航守卫 => 全局前置守卫
router.beforeEach((to, from, next) => {
  // 每次页面跳转，都会出发该函数
  // 只要注册了全局前置守卫，路由会立即瘫痪，必须要调用next() 方法来放行
  // 参数1：from从哪里来 参数2：to 到哪里去 参数3 next函数，决定是否放行，next(‘路径’)表示放行，跳转到哪个页面
  // 判断是否有登陆权证token
  // console.log(from)

  const token = getToken()
  if (token) {
    next()
  } else {
    // 以后白名单会越写越多，会导致写起来很麻烦，用数组的includes方法可以判断数组中的元素有没有符合的
    if (whiteList.includes(to.path)) {
      next()
    } else {
      Toast.fail('您还未登录，请登录')
      next('/login')
    }
  }
})

// 后置守卫
// router.afterEach()
export default router
